<template>
  <div class="diary-child-box">
    <div class="diary-child-operate">
      <div class="diary-child-operate-left">
        <je-input
          v-model:value="queryParam.keyWord"
          placeholder="搜索"
          autocomplete="false"
          class="left-search-box"
        >
          <template #prefix>
            <i class="fal fa-search" style="padding-right: 2px"></i>
          </template>
        </je-input>
      </div>
      <div class="diary-child-operate-right">
        <!-- <div class="diary-order-func">
          <div class="diary-popover">
            {{ queryParam.oderType == typeTime ? '功能排序' : '时间排序' }}</div
          >
          <i class="jeicon jeicon-a-function-on" @click="handleOrder"></i>
        </div>
        <div class="diary-order-func">
          <div class="diary-popover">全部已读</div>
          <i class="jeicon jeicon-envelope" @click="handleAllRead"></i>
        </div>
        <div class="diary-order-func">
          <div class="diary-popover">一键清空</div>
          <i class="jeicon jeicon-empty-on" @click="handleDelete('')"></i>
        </div> -->
        <je-tooltip placement="top">
          <template #title>
            <span>{{ queryParam.oderType == typeTime ? '功能排序' : '时间排序' }}</span>
          </template>
          <i class="jeicon jeicon-a-function-on" @click="handleOrder"></i>
        </je-tooltip>
        <je-tooltip placement="top">
          <template #title>
            <span>全部已读</span>
          </template>
          <i class="jeicon jeicon-envelope" @click="handleAllRead"></i>
        </je-tooltip>
        <je-tooltip placement="top">
          <template #title>
            <span>一键清空</span>
          </template>
          <i class="jeicon jeicon-empty-on" @click="handleDelete('')"></i>
        </je-tooltip>
      </div>
    </div>
    <div
      v-show="shareList.length > 0 && !loading"
      v-scrollBottom="loadMore"
      class="diary-child-info"
      :style="{ height: curHerght }"
    >
      <div
        v-for="shareItem in shareList"
        :key="shareItem.JE_MESSAGE_SHARE_ID"
        class="diary-child-info-item"
      >
        <div v-if="shareItem.SHAREDUSER_AVATAR" class="recore-avatar">
          <img :src="formatAvatar(shareItem.SHAREDUSER_AVATAR)" alt="" />
        </div>
        <div
          v-if="!shareItem.SHAREDUSER_AVATAR"
          class="diary-info-item-name"
          v-text="formatName(shareItem.SY_CREATEUSERNAME)"
        ></div>
        <div
          class="diary-info-item-read"
          :style="{ backgroundColor: shareItem.SHAREDUSER_YDZT_CODE == 0 ? '#ff625c' : '#a9aba9' }"
        ></div>
        <div class="diary-info-item-left">
          <div
            class="info-item-left-content"
            @click="
              handleRead(
                shareItem.SHARE_YWSJZJ,
                shareItem.SHAREDUSER_YDZT_CODE,
                shareItem.SHARE_FUNC_CODE,
                shareItem.JE_MESSAGE_SHARE_ID,
              )
            "
            v-html="shareItem.SHARE_TITLE"
          ></div>
          <div class="info-item-left-mark">
            <div v-html="shareItem.SHARE_FUNC_NAME"></div>
            <div>
              <i class="fal fa-alarm-clock"></i>
              <span v-text="formatTime(shareItem.SY_CREATETIME)"></span>
            </div>
          </div>
        </div>
        <div class="diary-info-item-right">
          <i class="jeicon jeicon-times" @click="handleDelete(shareItem.JE_MESSAGE_SHARE_ID)"></i>
        </div>
      </div>
      <div v-if="noMoreShow">
        <no-more-data />
      </div>
      <div v-if="loadMoreShow">
        <load-more-data />
      </div>
    </div>
    <div
      v-show="shareList.length == 0 && !loading"
      class="no-diary-info"
      :style="{ height: curHerght }"
      >暂无数据</div
    >
    <div v-show="loading" class="loading-box" :style="{ height: curHerght }">
      <load-more-data />
    </div>
  </div>
</template>

<script>
  import { defineComponent, reactive, toRefs, onMounted, watch, onBeforeUnmount } from 'vue';
  import { Input, Modal } from '@jecloud/ui';
  import { Tooltip } from 'ant-design-vue';
  import VueEvent from '@/helper/event';
  import { getCurrentUser, dateFormat, getFileUrlByKey, decode } from '@jecloud/utils';
  import { useMicroStore } from '@common/store/micro-store';
  import { showFuncForm } from '@jecloud/func';
  import { HOME_DIRAY_SHARE_HEIGHT } from '@/helper/constant';
  import { GetShareMyData, DeleteShareMe, UpdateShareMeRead } from '@/api';
  import directives from '@/helper/directives';
  import noMoreData from '@/views/board-home/components/no-more-data.vue';
  import loadMoreData from '@/views/board-home/components/load-more-data.vue';
  export default defineComponent({
    name: 'DirayShareGive',
    components: {
      JeInput: Input,
      JeTooltip: Tooltip,
      noMoreData,
      loadMoreData,
    },
    directives: directives,
    emits: ['noReadShare'],
    setup(props, { emit }) {
      const microStore = useMicroStore();
      const typeCode = 'SHARED'; //分享类型
      let searchTimeout = null; //搜索定时器
      let curYear = new Date().getFullYear(); //当前时间年份
      const state = reactive({
        curHerght: window.sessionStorage.getItem(HOME_DIRAY_SHARE_HEIGHT), //当前内容区域高度
        typeTime: 'time', //排序方式 时间
        typeFunc: 'func', //排序方式 功能
        queryParam: {
          userId: getCurrentUser()?.id, //用户id
          deptId: getCurrentUser()?.organization.id, //部门id
          keyWord: '', //关键字
          oderType: 'time', //排序方式 time/时间 func/功能
          page: 1, //当前页
          limit: 30, //每页条数
        },
        shareList: [], //收藏列表
        pages: 1, //总分页数
        updateFlag: true, //更新已读状态标注
        notReadNum: 0, //共享给我未读的数量
        noMoreShow: false, //没有更多数据
        loadMoreShow: false, //滑动过程中加载数据
        loading: false, //接口请求数据时加载中
      });
      const methods = {
        loadShareData() {
          //加载分享给我的列表
          GetShareMyData(state.queryParam).then((res) => {
            if (res.code == 1000 && res.success) {
              const resData = res.data;
              state.shareList = state.shareList.concat(resData.rows);
              if (state.queryParam.keyWord && state.shareList.length > 0) {
                state.shareList.forEach((item) => {
                  //标题高亮
                  item.SHARE_TITLE = item.SHARE_TITLE.replaceAll(
                    state.queryParam.keyWord,
                    `<span class="hight-str">${state.queryParam.keyWord}</span>`,
                  );
                  //功能名称
                  item.SHARE_FUNC_NAME = item.SHARE_FUNC_NAME.replaceAll(
                    state.queryParam.keyWord,
                    `<span class="hight-str">${state.queryParam.keyWord}</span>`,
                  );
                });
              }
              state.notReadNum = resData.notRead ? resData.notRead : 0;
              state.pages = resData.pages ? resData.pages : 1;
              state.loadMoreShow = false;
              state.loading = false;
              emit('noReadShare', state.notReadNum);
            }
          });
        },
        noLoadShardData() {
          //没有load的获取数据
          GetShareMyData(state.queryParam).then((res) => {
            if (res.code == 1000 && res.success) {
              const resData = res.data;
              state.shareList = [];
              state.shareList = state.shareList.concat(resData.rows);
              if (state.queryParam.keyWord && state.shareList.length > 0) {
                state.shareList.forEach((item) => {
                  //标题高亮
                  item.SHARE_TITLE = item.SHARE_TITLE.replaceAll(
                    state.queryParam.keyWord,
                    `<span class="hight-str">${state.queryParam.keyWord}</span>`,
                  );
                  //功能名称
                  item.SHARE_FUNC_NAME = item.SHARE_FUNC_NAME.replaceAll(
                    state.queryParam.keyWord,
                    `<span class="hight-str">${state.queryParam.keyWord}</span>`,
                  );
                });
              }
              if (resData.notRead) {
                state.notReadNum = resData.notRead;
                state.pages = resData.pages;
              }
            }
          });
        },
        formatName(name) {
          //格式化名字
          if (name) {
            return name.slice(name.length - 2);
          }
        },
        formatTime(createTime) {
          //时间显示转化格式
          const curDate = new Date(createTime);
          let temYear = dateFormat(curDate, 'YYYY');
          if (temYear == curYear) {
            return dateFormat(curDate, 'MM-DD');
          } else {
            return dateFormat(curDate, 'YYYY-MM-DD');
          }
        },
        handleDelete(shardId = '') {
          //删除分享给我的
          const deleteMsg = shardId === '' ? '确定要删除全部吗' : '确定要删除吗？';
          Modal.alert({
            content: `${deleteMsg}`,
            status: 'warning',
            okButton: () => {
              const param = {
                userId: state.queryParam.userId,
                deptId: state.queryParam.deptId,
                JE_MESSAGE_SHARE_ID: shardId,
              };
              DeleteShareMe(param).then((res) => {
                if (res.code == 1000 && res.success) {
                  Modal.notice(res.message, 'success');
                  if (shardId) {
                    //删除单条数据
                    state.shareList = state.shareList.filter((curItem) => {
                      return curItem.JE_MESSAGE_SHARE_ID != shardId;
                    });
                    state.notReadNum -= 1;
                    emit('noReadShare', state.notReadNum);
                  } else {
                    //删除全部数据
                    state.shareList = [];
                    state.notReadNum = 0;
                    emit('noReadShare', state.notReadNum);
                  }
                }
              });
            },
            cancelButton: () => {
              //关闭弹窗
            },
          });
        },
        handleOrder() {
          //功能/时间排序
          state.queryParam.oderType =
            state.queryParam.oderType === state.typeTime ? state.typeFunc : state.typeTime;
          state.queryParam.page = 1;
          state.shareList = [];
          state.loading = true;
          methods.loadShareData();
        },
        handleRead(shardId, shareReadStatus, funcCode, messageShareId) {
          //查看并标记已读状态
          if (shareReadStatus == 0) {
            //未读需要标识为已读
            if (state.updateFlag) {
              const param = {
                userId: state.queryParam.userId,
                deptId: state.queryParam.deptId,
                JE_MESSAGE_SHARE_ID: messageShareId,
              };
              state.updateFlag = false;
              UpdateShareMeRead(param).then((res) => {
                if (res.code == 1000 && res.success) {
                  state.updateFlag = true;
                  //更新已读状态
                  state.shareList.forEach((item) => {
                    if (item.JE_MESSAGE_SHARE_ID == messageShareId) {
                      item.SHAREDUSER_YDZT_CODE = '1';
                    }
                  });
                  showFuncForm(funcCode, {
                    beanId: shardId,
                  });
                } else {
                  Modal.notice(res.message, 'error');
                  state.updateFlag = true;
                }
              });
            }
          } else {
            showFuncForm(funcCode, {
              beanId: shardId,
            });
          }
        },
        handleAllRead() {
          //全部已读
          if (state.updateFlag) {
            const param = {
              userId: state.queryParam.userId,
              deptId: state.queryParam.deptId,
              JE_MESSAGE_SHARE_ID: '',
            };
            state.updateFlag = false;
            UpdateShareMeRead(param).then((res) => {
              if (res.code == 1000 && res.success) {
                state.updateFlag = true;
                Modal.notice(res.message, 'success');
                //更新已读状态
                state.shareList.forEach((item) => {
                  item.SHAREDUSER_YDZT_CODE = '1';
                });
              } else {
                Modal.notice(res.message, 'error');
                state.updateFlag = true;
              }
            });
          }
        },
        changeHeight() {
          //更改内容显示区域高度变化
          state.curHerght = window.sessionStorage.getItem(HOME_DIRAY_SHARE_HEIGHT);
        },
        loadMore() {
          //滚动底部加载更多
          if (state.queryParam.page < state.pages) {
            state.loadMoreShow = true;
            state.queryParam.page += 1;
            methods.loadShareData();
          } else {
            state.loadMoreShow = false;
            state.noMoreShow = true;
          }
        },
        socketMessage(message) {
          //监听socket分享给我的信息
          if (message.busType == 'MSG') {
            //推送通知类型与当前选中类型相同，需要刷新数据
            const messageData = JSON.parse(message.content);
            if (messageData.code == typeCode) {
              //动态添加数据
              const curSharedItem = messageData.data.values;
              curSharedItem.SHAREDUSER_YDZT_CODE = '0';
              state.shareList.unshift(curSharedItem);
            }
          }
        },
        formatAvatar(avatarStr) {
          //头像转换
          const avatarObj = decode(avatarStr);
          if (Array.isArray(avatarObj)) {
            return getFileUrlByKey(avatarObj[0].fileKey);
          } else {
            return getFileUrlByKey(avatarObj.fileKey);
          }
        },
      };
      watch(
        //监听搜索
        () => state.queryParam.keyWord,
        (newVal, oldVal) => {
          if (newVal !== oldVal) {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
              state.queryParam.page = 1;
              // state.shareList = [];
              // methods.loadShareData();
              methods.noLoadShardData();
            }, 1000);
          }
        },
      );
      //注册websocket监听事件-分享给我
      microStore.on('websocket-message', (message) => {
        methods.socketMessage(message);
      });
      onMounted(() => {
        state.queryParam.page = 1;
        state.loading = true;
        methods.loadShareData();
        methods.changeHeight();
        VueEvent.on(HOME_DIRAY_SHARE_HEIGHT, methods.changeHeight);
      });
      onBeforeUnmount(() => {
        clearTimeout(searchTimeout);
        VueEvent.off(HOME_DIRAY_SHARE_HEIGHT);
      });
      return {
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style scoped lang="less">
  .diary-child-box {
    width: 100%;
    height: 100%;
    .diary-child-operate {
      width: 100%;
      height: 40px;
      display: inline-flex;
      justify-content: space-between;
      align-items: center;
      padding-left: 20px;
      padding-right: 10px;
      .diary-child-operate-left {
        .ant-input-affix-wrapper {
          width: 220px;
          border: 1px solid #f5f5f5;
        }
      }
      .diary-child-operate-right {
        display: inline-flex;
        i {
          font-size: 12px;
          color: #808d9f;
          margin-left: 6px;
          cursor: pointer;
        }
        .diary-order-func {
          position: relative;
          z-index: 10;
          .diary-popover {
            width: 54px;
            height: 20px;
            line-height: 20px;
            position: absolute;
            top: -20px;
            left: -17px;
            text-align: center;
            font-size: 12px;
            color: #ffffff;
            background-color: #2d3b41;
            border-radius: 2px;
            display: none;
          }
        }
        .diary-order-func:hover .diary-popover {
          display: block;
        }
      }
    }
    .diary-child-info {
      width: 100%;
      overflow-y: auto;
      .diary-child-info-item {
        width: 100%;
        display: inline-flex;
        // align-items: center;
        position: relative;
        padding: 10px 10px 10px 20px;
        .recore-avatar {
          width: 34px;
          height: 34px;
          text-align: center;
          border-radius: 100%;
          margin-left: 6px;
          img {
            width: 34px;
            height: 34px;
            border-radius: 100%;
          }
        }
        .diary-info-item-name {
          width: 34px;
          height: 34px;
          line-height: 34px;
          border-radius: 50%;
          text-align: center;
          font-size: 12px;
          color: #ffffff;
          background-color: #faa03a;
          flex-shrink: 0;
          margin-left: 6px;
        }
        .diary-info-item-read {
          width: 6px;
          height: 6px;
          border-radius: 50%;
          position: absolute;
          left: 15px;
          top: 27px;
        }
        .diary-info-item-left {
          width: 210px;
          margin-left: 10px;
          .info-item-left-content {
            width: 100%;
            max-height: 40px;
            line-height: 18px;
            font-size: 14px;
            color: #3f3f3f;
            overflow: hidden;
            text-overflow: ellipsis;
            -webkit-box-orient: vertical;
            display: -webkit-box;
            -webkit-line-clamp: 2;
          }
          .info-item-left-mark {
            width: 100%;
            height: 18px;
            line-height: 18px;
            display: inline-flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 4px;
            color: #a9aba9;
            font-size: 12px;
            span {
              padding-left: 4px;
            }
          }
        }
        .diary-info-item-right {
          cursor: pointer;
          display: none;
          margin-left: 7px;
          i {
            font-size: 12px;
            color: #a9aba9;
          }
        }
      }
      .diary-child-info-item:hover {
        background: #f7f9ff;
        .diary-info-item-left .info-item-left-content {
          color: @primary-color;
          cursor: pointer;
        }
        .diary-info-item-right {
          display: block;
        }
      }
    }
    .diary-child-info::-webkit-scrollbar {
      width: 0;
      height: 0;
    }
    .no-diary-info {
      width: 100%;
      display: flex;
      justify-content: center;
      padding-top: 50px;
      font-size: 14px;
      color: #3f3f3f;
    }
    .loading-box {
      width: 100%;
      padding-top: 50px;
    }
  }
</style>
